package com.tnxst.phexamination.activity;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.SavedStateViewModelFactory;
import androidx.lifecycle.ViewModelProvider;

import com.tnxst.phexamination.R;
import com.tnxst.phexamination.constant.Constant;
import com.tnxst.phexamination.databinding.ActivityDataSyncBinding;
import com.tnxst.phexamination.dto.DiabetesFollowDTO;
import com.tnxst.phexamination.dto.InhabitantDTO;
import com.tnxst.phexamination.dto.ServicePackageDTO;
import com.tnxst.phexamination.dto.SignDTO;
import com.tnxst.phexamination.fragment.RecordTcmHealthElderlyFragment;
import com.tnxst.phexamination.public_health_docking_interface.FamilySignInterface;
import com.tnxst.phexamination.public_health_docking_interface.InhabitantInterface;
import com.tnxst.phexamination.public_health_docking_interface.SyncInterface;
import com.tnxst.phexamination.utils.GsonUtils;
import com.tnxst.phexamination.utils.ReflectUtils;
import com.tnxst.phexamination.utils.Utils;
import com.tnxst.phexamination.utils.WebServiceUtils;
import com.tnxst.phexamination.viewmodel.GlobalViewModel;
import com.tnxst.phexamination.vo.SignVo;
import com.tnxst.phexamination.vo.TeamVo;
import com.tnxst.phexamination.vo.UserInfoVo;

import org.apache.commons.collections.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class DataSyncActivity extends BaseActivity implements View.OnClickListener {
    private GlobalViewModel viewModel;

    private ActivityDataSyncBinding binding;

    private Context context;

    private AlertDialog show;

    private static Integer pageSize = 1000;

    private FragmentManager fragmentManager;

    private RecordTcmHealthElderlyFragment fragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewModel = new ViewModelProvider(this, new SavedStateViewModelFactory(getApplication(), this)).get(GlobalViewModel.class);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_data_sync);
        binding.setDataSync(viewModel);
        binding.setLifecycleOwner(this);
        context = this;
        fragmentManager = getSupportFragmentManager();
        initView();
    }

    private void initView() {
        binding.textView26.setOnClickListener(this);
        binding.textView28.setOnClickListener(this);
        binding.textView47.setOnClickListener(this);
        binding.textView46.setOnClickListener(this);
        binding.textView48.setOnClickListener(this);
        binding.textView49.setOnClickListener(this);
        binding.textView50.setOnClickListener(this);
        binding.textView51.setOnClickListener(this);
        binding.textView52.setOnClickListener(this);
        binding.textView42.setText(viewModel.getSharedPreferences().getString(Constant.INHABITANT_SYNC_DATE,"（从未同步）"));
        binding.textView34.setText(viewModel.getSharedPreferences().getString(Constant.SIGN_TEAM_SYNC_DATE,"（从未同步）"));
        binding.textView43.setText(viewModel.getSharedPreferences().getString(Constant.SERVICE_PACKAGE_SYNC_DATE,"（从未同步）"));
        binding.textView45.setText(viewModel.getSharedPreferences().getString(Constant.SIGN_SYNC_DATE,"（从未同步）"));
    }

    private void loading(){
        final AlertDialog.Builder alertDialog = new AlertDialog.Builder(context,R.style.AlertDialog);
        View view = View.inflate(context, R.layout.login_loading, null);
        alertDialog
                .setView(view)
                .create();
        show = alertDialog.show();
        show.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        show.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        TextView textView = show.findViewById(R.id.imageView1);
        textView.setText("正在同步");
        show.setCancelable(false);
        AnimationDrawable ad = (AnimationDrawable) textView.getCompoundDrawables()[1];
        ad.start();
        show.dismiss();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.textView26:
                finish();
                break;
            case R.id.textView28:

                break;
            case R.id.textView47:
//                showFragment();
                SyncInterface.syncDoctorList(this,viewModel);
                break;
            case R.id.textView46:

//                syncSignTeamData();
                break;
            case R.id.textView48:
                break;
            case R.id.textView49:

//                syncInhabitantData(0);
                SyncInterface.syncInhabitantList(this,viewModel);
                break;
            case R.id.textView50:

//                syncServicePackage();
                break;
            case R.id.textView51:
                List<DiabetesFollowDTO> all = viewModel.getDiabetesFollowRepository().findAll();
                if (!CollectionUtils.isEmpty(all)){
                    for (DiabetesFollowDTO diabetesFollowDTO : all) {
                        SyncInterface.syncAddFollowDiabetes(this,diabetesFollowDTO);
                    }
                }
                break;
            case R.id.textView52:

//                syncSignData();
                break;
        }
    }

//    private void syncSignData() {
//        //上传更新的签约
//        List<SignDTO> upload = viewModel.getSignRepository().findByFieldList("upload", false);
//        if (CollectionUtils.isEmpty(upload)){
//            Utils.Toast(context,"暂无数据同步！");
//            show.dismiss();
//            return;
//        }
//        for (SignDTO signDTO : upload) {
//            SignVo signVo = new SignVo();
//            signVo.setContractID(signDTO.getCONTRACTID());
//            signVo.setTags(signDTO.getTAGS());
//            signVo.setTeamEmpId(signDTO.getTEAM_EMP_ID());
//            signVo.setTeamID(signDTO.getTEAMID());
//            signVo.setPERSON_ID(signDTO.getPERSONID());
//            signVo.setSignDate(signDTO.getSIGNDATE());
//            signVo.setOtheremark(signDTO.getOTHEREMARK());
//            signVo.setEndTime(signDTO.getENDTIME());
//            signVo.setStartTime(signDTO.getSTARTTIME());
//            signVo.setContractServices(signDTO.getContractServices());
//            signVo.setFee(signDTO.getFEE());
//            signVo.setChannel(signDTO.getCHANNEL());
//            signVo.setSignPerson(signDTO.getSIGNPERSON());
//            FamilySignInterface.familyDoctorSign(signVo, new WebServiceUtils.Response() {
//                @Override
//                public void onSuccess(Object result) {
//                    signDTO.setUpload(true);
//                    viewModel.getSignRepository().insert(signDTO);
//                    show.dismiss();
//                }
//
//                @Override
//                public void onError(String error) {
//                    Utils.Toast(context,"上传" + signDTO.getPERSONNAME() + "的签约失败！\n失败原因：" + error);
//                    show.dismiss();
//                }
//            });
//        }
//        Utils.Toast(context,"上传成功！");
//
//    }

//    private void syncSignTeamData() {
//        FamilySignInterface.getTeamInfo(1, "", 100, 0, new WebServiceUtils.Response<List>() {
//            @Override
//            public void onSuccess(List result) {
//                UserInfoVo userInfo = viewModel.getUserInfo();
//                List<TeamVo> teamVos = new ArrayList<>();
//                for (Object o : result) {
//                    Map data = (Map) o;
//                    TeamVo teamVo =(TeamVo) ReflectUtils.mapToObject(data, TeamVo.class);
//                    teamVos.add(teamVo);
//                }
//                userInfo.setTeamVos(teamVos);
//                //储存登录返回结果
//                viewModel.getSharedPreferences().edit().putString(Constant.LOGIN_RESULT, GsonUtils.toJson(userInfo)).apply();
//                Utils.Toast(context,"同步签约团队数据成功!");
//                show.dismiss();
//                SharedPreferences.Editor edit = viewModel.getSharedPreferences().edit();
//                String now = "上次同步时间：" + Utils.getStringFromDate(new Date());
//                edit.putString(Constant.SIGN_TEAM_SYNC_DATE,now);
//                edit.apply();
//                binding.textView34.setText(now);
//            }
//
//            @Override
//            public void onError(String error) {
//                Utils.Toast(context,"同步签约团队信息失败！\n" + error);
//                show.dismiss();
//            }
//        });
//    }

//    private void syncServicePackage(){
//        FamilySignInterface.getOrgServicePack(null, 10, new WebServiceUtils.Response<List>() {
//            @Override
//            public void onSuccess(List result) {
//                ServicePackageDTO[] servicePackageDTOS = new ServicePackageDTO[result.size()];
//                for (int i = 0; i < result.size(); i++) {
//                    Map map = (Map) result.get(i);
//                    ServicePackageDTO packageDTO = (ServicePackageDTO) ReflectUtils.mapToObject(map, ServicePackageDTO.class);
//                    servicePackageDTOS[i] = packageDTO;
//                }
//                viewModel.getServicePackageRepository().insert(servicePackageDTOS);
//            }
//            @Override
//            public void onError(String error) {
//                Utils.Toast(DataSyncActivity.this,"失败原因：" + error);
//                show.dismiss();
//            }
//        });
//        FamilySignInterface.getOrgServicePack(null, 11, new WebServiceUtils.Response<List>() {
//            @Override
//            public void onSuccess(List result) {
//                ServicePackageDTO[] servicePackageDTOS = new ServicePackageDTO[result.size()];
//                for (int i = 0; i < result.size(); i++) {
//                    Map map = (Map) result.get(i);
//                    ServicePackageDTO packageDTO = (ServicePackageDTO) ReflectUtils.mapToObject(map, ServicePackageDTO.class);
//                    servicePackageDTOS[i] = packageDTO;
//                }
//                viewModel.getServicePackageRepository().insert(servicePackageDTOS);
//                SharedPreferences.Editor edit = viewModel.getSharedPreferences().edit();
//                String now = "上次同步时间：" + Utils.getStringFromDate(new Date());
//                edit.putString(Constant.SERVICE_PACKAGE_SYNC_DATE,now);
//                edit.apply();
//                binding.textView43.setText(now);
//                show.dismiss();
//                Utils.Toast(context,"同步服务包数据成功!");
//            }
//            @Override
//            public void onError(String error) {
//                Utils.Toast(DataSyncActivity.this,"失败原因：" + error);
//                show.dismiss();
//            }
//        });
//    }


//    public void syncInhabitantData(Integer pageIndex){
//        InhabitantInterface.queryInhabitantBasicInfo(null,pageSize, pageIndex, new WebServiceUtils.Response<List>() {
//            @Override
//            public void onSuccess(List result) {
//                List<InhabitantDTO> inhabitantDTOS = new ArrayList<>();
//                for (Object o : result) {
//                    Map map = (Map) o;
//                    InhabitantDTO inhabitantDTO = ReflectUtils.mapToObject(map, InhabitantDTO.class);
//                    inhabitantDTOS.add(inhabitantDTO);
//                }
//                viewModel.getInhabitantRepository().insert(inhabitantDTOS.toArray(new InhabitantDTO[inhabitantDTOS.size()]));
//                if (result.size() >= pageSize){
//                    syncInhabitantData(pageIndex + 1);
//                }else {
//                    Utils.Toast(context,"同步居民数据成功!");
//                    show.dismiss();
//                    SharedPreferences.Editor edit = viewModel.getSharedPreferences().edit();
//                    String now = "上次同步时间：" + Utils.getStringFromDate(new Date());
//                    edit.putString(Constant.INHABITANT_SYNC_DATE,now);
//                    edit.apply();
//                    binding.textView42.setText(now);
//                }
//            }
//
//            @Override
//            public void onError(String error) {
//                Utils.Toast(context,"同步居民数据失败! \n" + error);
//                show.dismiss();
//            }
//        });
//    }
}
